<template>
  <div class="vehicle-management">
    <!-- 操作栏：按钮 + 搜索 -->
    <div class="operation-bar">
      <el-button type="primary" @click="showAddDialog">添加</el-button>
      <div class="search-group" style="margin-left: auto;">
        <el-input
          placeholder="请输入车牌号"
          v-model="searchInput"
          style="width: 240px;"
        />
        <el-button type="primary" icon="el-icon-search" @click="searchVehicles"></el-button>
        <el-button type="primary" icon="el-icon-filter"></el-button>
      </div>
    </div>

    <!-- 车辆信息表格 -->
    <el-table :data="tableData" border style="width: 100%; margin-bottom: 20px;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="communityName" label="小区名称" width="100" />
      <el-table-column prop="carPlate" label="登记车牌" width="100" />
      <el-table-column prop="homeownerName" label="车主" width="80" />
      <el-table-column prop="homeownerPhone" label="联系方式" width="120" />
      
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="editVehicle(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="deleteVehicle(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrap">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="prev, pager, next, ->, jumper, ->, sizes, total"
        :total="total"
      />
    </div>

    <!-- 添加/编辑车辆对话框 -->
    <el-dialog
      :title="dialogMode === 'add' ? '添加车辆' : '编辑车辆'"
      :visible.sync="dialogVisible"
      width="30%"
      @close="resetForm"
    >
      <el-form ref="vehicleForm" :model="form" label-width="150px">
        <el-form-item label="小区*" prop="community">
          <el-select v-model="form.community" placeholder="请选择" @change="handHomeownerChange">
            <el-option
              v-for="item in neighborhoods"
              :key="item.label"
              :label="item.value"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="登记车牌*" prop="carPlate">
          <el-input v-model="form.licensePlate" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="车主*" prop="homeownerName">
          <el-select v-model="form.owner" placeholder="请选择" >
            <el-option
              v-for="item in homeowners"
              :key="item.label"
              :label="item.value"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveVehicle">{{ dialogMode === 'add' ? '保存' : '更新' }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>


export default {
  name: 'VehicleManagement',
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      searchInput: '',
      selectedRows: [],
      dialogVisible: false, // 控制对话框显示
      form: { // 表单数据
        community: '',
        licensePlate: '',
        owner: '',
       carId:'',
      },
      // 定义小区选项
      neighborhoods: [],
      // 定义业主选项
      homeowners: [],
      dialogMode: 'add', // 对话框模式：'add' 或 'edit'
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.getVehicles(this.currentPage);
      this.getNeighborhoods();
      this.getHomeowners();
    });
  },
  methods: {
    // 获取所有车辆信息
    getVehicles(pageNum) {
      this.$axios.post('http://192.168.214.129:8080/car/all', {
        carTitle: this.searchInput,
        pageNum: pageNum,
        pageSize: this.pageSize,
      })
      .then(resp => {
        console.log(resp);
        if (resp.data.code === 200) {
          this.tableData = resp.data.data.records;
          this.total = resp.data.data.total;
          this.currentPage = resp.data.data.current;
        }
      })
      .catch(error => {
        console.error('获取车辆信息失败', error);
      });
    },

    // 获取所有小区，展示在添加/编辑车辆对话框中
    getNeighborhoods() {
      this.$axios.get('http://192.168.214.129:8080/community/selcomm')
      .then(resp => {
        if (resp.data.code === 200) {
          this.neighborhoods = resp.data.data.map(item => {
            return { value: item.communityName, label: item.communityId };
          });
          console.log(resp);
        }
      })
      .catch(error => {
        console.error('获取小区信息失败', error);
      });
    },

    handHomeownerChange(commId){
      
      if(commId){
        this.getHomeowners(commId);
      }
    },

    // 获取所有业主，展示在添加/编辑车辆对话框中
    getHomeowners(commId) {
      this.$axios.get('http://192.168.214.129:8080/homeowner/homeownerbyid',{
        params: {
              commId:commId
        }
      })
      .then(resp => {
        if (resp.data.code === 200) {
          this.homeowners = resp.data.data.map(item => {
            return { value: item.homeownerName, label: item.homeownerId };
          });
          console.log(resp);
        }
      })
      .catch(error => {
        console.error('获取业主信息失败', error);
      });
    },

    // 展示添加车辆对话框
    async showAddDialog() {
      this.dialogVisible = true;
      this.dialogMode = 'add'; // 设置对话框模式为添加
      this.resetForm(); // 重置表单
      await this.getNeighborhoods(); // 确保小区列表加载完成
      await this.getHomeowners(); // 确保业主列表加载完成
    },

    // 重置表单
    resetForm() {
      this.form = {
        community: '',
        licensePlate: '',
        owner: '',
        phone: '',
        relatedParking: '',
      };
    },

    // 保存车辆信息
    saveVehicle() {
      console.log(this.carId);
      
      const vehicle = {
        carId:this.carId,
        communityId: this.form.community,
        carPlate: this.form.licensePlate,
        homeownerId: this.form.owner,
      };
      console.log('保存车辆信息:', vehicle);

      // 关闭对话框
      this.dialogVisible = false;

      // 向后端发送保存请求
      if (this.dialogMode === 'add') {
        this.$axios.post('http://192.168.214.129:8080/car/addcar', vehicle)
          .then(resp => {
            if (resp.data.code === 200) {
              this.$message.success('车辆添加成功');
              this.resetForm();
              this.getVehicles(this.currentPage); // 刷新表格数据
            } else {
              this.$message.error('车辆添加失败');
            }
          })
          .catch(error => {
            console.error('保存车辆信息失败', error);
            this.$message.error('保存失败，请重试');
          });
      } else if (this.dialogMode === 'edit') {
        this.$axios.put('http://192.168.214.129:8080/car/editcar', vehicle)
          .then(resp => {
            if (resp.data.code === 200) {
              this.$message.success('车辆编辑成功');
              this.resetForm();
              this.getVehicles(this.currentPage); // 刷新表格数据
            } else {
              this.$message.error('车辆编辑失败');
            }
          })
          .catch(error => {
            console.error('编辑车辆信息失败', error);
            this.$message.error('编辑失败，请重试');
          });
      }
    },

    // 搜索车辆信息
    searchVehicles() {
      this.getVehicles(this.currentPage);
    },

    // 获取车辆详细信息
    getVehicleDetails(vehicleId) {
      this.$axios.get(`http://192.168.214.129:8080/car/carbyid`,{
        params: {
          carId: vehicleId
        }
      })
        .then(resp => {
          console.log(resp);
          if (resp.data.code === 200) {
            const vehicle = resp.data.data;
            this.carId=vehicle.carId;
            this.form = {
              community: vehicle.communityId,
              licensePlate: vehicle.carPlate,
              owner: vehicle.homeownerName,
            };
            
          }
        })
        .catch(error => {
          console.log(error);
          
          console.error('获取车辆详细信息失败', error);
          this.$message.error('获取详细信息失败，请重试');
        });
    },

    // 编辑车辆
    editVehicle(row) {
      console.log(row.carId);
      
      this.dialogMode = 'edit';
      this.getVehicleDetails(row.carId);
      this.dialogVisible = true;
    },

    // 删除车辆
    deleteVehicle(row) {
      this.$confirm('将删除车辆, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteVehicleMethod(row.carId);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },

    // 删除车辆的方法
    deleteVehicleMethod(carId) {
      this.$axios.delete(`http://192.168.214.129:8080/car/delcar/${carId}`)
        .then(resp => {

          console.log(resp);
          
          if (resp.data.code === 200) {
            this.$message.success('删除成功');
            this.getVehicles(this.currentPage); // 刷新表格数据
          } else {
            this.$message.error('删除失败');
          }
        })
        .catch(error => {
          console.error('删除车辆失败', error);
          this.$message.error('删除失败，请重试');
        });
    },

    // 处理表格选择变化
    handleSelectionChange(val) {
      this.selectedRows = val.map(row => row.vehicleId);
    },

    // 处理分页大小变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.getVehicles(this.currentPage);
    },

    // 处理当前页变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getVehicles(this.currentPage);
    },

    
  }
};
</script>

<style scoped>
.vehicle-management {
  padding: 20px;
}

.operation-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.search-group {
  display: flex;
  align-items: center;
}

.search-group .el-input {
  margin-right: 8px;
}

.pagination-wrap {
  display: flex;
  justify-content: flex-end;
}
</style>
